<template>
  <el-dialog
    v-bind="$attrs"
    width="600px"
    :title="$t('flyparam.new_terminal')"
    v-on="$listeners"
    @open="open"
    @close="close"
  >
    <el-form ref="form" :model="form" @submit.native.prevent>
      <el-form-item
        size="small"
        :label="$t('common.device_sn')"
        required
        prop="rowUniqueKey"
        :rules="rules"
      >
        <el-input
          v-model.trim="form.rowUniqueKey"
          @blur="() => (form.rowUniqueKey = form.rowUniqueKey.trim())"
          @keyup.enter.native="confirm"
        />
      </el-form-item> </el-form
    ><template #footer>
      <div>
        <el-button size="small" @click="close">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="confirm"
          >{{ $t('common.confirm') }}</el-button
        >
      </div></template
    >
  </el-dialog>
</template>

<script>
import { addProfileEntry } from '@/api/parameter'
import { validateSN } from '../validate'
export default {
  props: {
    info: {
      type: Object
    }
  },
  data() {
    return {
      loading: false,
      form: {
        rowUniqueKey: ''
      }
    }
  },
  computed: {
    rules() {
      return validateSN
    }
  },
  methods: {
    open() {},
    close() {
      this.$emit('update:model-value', false)
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          addProfileEntry({
            templateId: this.$route.params.id,
            tableId: this.info.entryId,
            rowUniqueKey: this.form.rowUniqueKey,
            isTerminal: true
          })
            .then((newEntry) => {
              this.$message.success(this.$t('common.message.operation_success'))
              this.close()
              this.$emit('confirm', newEntry)
              bus.$emit('freshTerminalCount')
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style>
</style>
